package com.cysyz.web.modules.base.validatecode.controller;

import com.cysyz.mylib.utils.MyStringUtils;
import com.cysyz.mylib.utils.images.ValidateCode;
import com.cysyz.mylib.utils.myassert.MyAssert;
import com.cysyz.web.modules.base.support.controller.SpringMVCBaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public abstract class AbstractValidateCodeController extends SpringMVCBaseController {

    @RequestMapping("/getCode")
    @ResponseBody
    public void getValidateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //返回验证码需要对response进行配置
        configResponse(response);

        responseValidateCode(request, response);
    }

    @RequestMapping("/checkCode")
    @ResponseBody
    public String checkValidateCode(String validateCodeInput) {
        MyAssert.hasText(validateCodeInput);

        Boolean checkSuccess = false;

        String validateCodeInSession = (String) getSession().getAttribute(getValidateCodeKey());
        if (MyStringUtils.hasText(validateCodeInSession) && validateCodeInSession.equalsIgnoreCase(validateCodeInput)) {
            checkSuccess = true;
        }

        return checkSuccess.toString();
    }

    private void configResponse(HttpServletResponse response) {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
    }

    private void responseValidateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();

        ValidateCode vCode = new ValidateCode(120,40,5,100);
        session.setAttribute(getValidateCodeKey(), vCode.getCode());

        vCode.write(response.getOutputStream());
    }

    private String getValidateCodeKey() {

        return this.getClass().getName();

    }


}



